package top.codef.sqlfilter;

import java.lang.reflect.Field;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;

import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToMany;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Path;
import top.codef.exceptions.JpaAmebaException;

public class PathUtils {

	public static Expression<?> getPath(String pahtName, Expression<?> path) {
		if (StringUtils.isBlank(pahtName))
			throw new JpaAmebaException("不存在的字段信息");
		for (String speratedField : pahtName.split("\\.")) {
			if (StringUtils.isBlank(speratedField))
				throw new JpaAmebaException("字段信息不正确");
			if (Path.class.isAssignableFrom(path.getClass())) {
				var thePath = (Path<?>) path;
				path = thePath.get(speratedField);
			}
		}
		return path;
	}

	// 临时方案
	public static SubCommonFilter<?, ?> confirmOneToManySubQ(CommonFilter filter, String field, Expression<?> path) {
		if (!field.contains("."))
			return null;
		var fStr = field.split("\\.")[0];
		var clazz = path.getJavaType();
		var one2ManyField = FieldUtils.getDeclaredField(clazz, fStr);
		if (one2ManyField == null)
			throw new JpaAmebaException("can`t find field");
		if (one2ManyField.getAnnotation(OneToMany.class) == null)
			return null;
		if (filter.getSubQuery().get(one2ManyField.toString()) == null) {
			var joinColumn = one2ManyField.getAnnotation(JoinColumn.class);
			if (joinColumn == null)
				throw new JpaAmebaException("no JoinColumn annotation");
			Field fkField = StringUtils.isBlank(joinColumn.referencedColumnName())
					? FieldUtils.getFieldsListWithAnnotation(clazz, Id.class).stream().findFirst().orElse(null)
					: FieldUtils.getField(clazz, joinColumn.referencedColumnName());
			return filter.subQ(one2ManyField, fkField.getType()).fkField(fkField.getName());
		} else {
			return filter.getSubQuery().get(one2ManyField.toString());
		}
	}
}
